package cn.com.css.taxInspection.system.controller;

import cn.com.css.taxInspection.common.config.FileUploadProperties;
import cn.com.css.taxInspection.common.result.DataResult;
import cn.com.css.taxInspection.system.service.HomeService;
import cn.com.css.taxInspection.system.service.PermissionService;
import cn.com.css.taxInspection.system.service.impl.HttpSessionService;
import cn.com.css.taxInspection.workrisk.entity.WorkriskControlEntity;
import cn.com.css.taxInspection.workrisk.entity.WorkriskRisk1Entity;
import cn.com.css.taxInspection.workrisk.service.WorkriskControlService;
import cn.com.css.taxInspection.workrisk.service.WorkriskRisk1Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 */
@Slf4j
@RestController
@RequestMapping("/sys")
@Api(tags = "首页数据")
public class HomeController {
    @Resource
    private HomeService homeService;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private FileUploadProperties fileUploadProperties;
    @Resource
    private WorkriskControlService workriskControlService;
    @Resource
    private WorkriskRisk1Service workriskRisk1Service;
    @Resource
    private PermissionService permissionService;

    @GetMapping("/home")
    @ApiOperation(value = "获取首页数据接口")
    public DataResult getHomeInfo() {
        // 通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        DataResult result = DataResult.success();
        result.setData(homeService.getHomeInfo(userId));
        return result;
    }

    @GetMapping("/menuSearch")
    @ApiOperation(value = "首页菜单搜索")
    public DataResult menuSearch(String menuName) {
        String currentIdentityNo = httpSessionService.getCurrentIdentityNo();
        return DataResult.success(permissionService.searchPermissionTreeList(currentIdentityNo, menuName));
    }

    @PostMapping("/getXxtx")
    @ApiOperation(value = "获取首页数据接口")
    public DataResult getXxtx() {
        String currentUserId = httpSessionService.getCurrentUserId();
        String currentRolesId = httpSessionService.getCurrentRolesId();
        String currentDeptId = httpSessionService.getCurrentDeptId();

        // 督办数量
        LambdaQueryWrapper<WorkriskControlEntity> queryWrapper1 = Wrappers.lambdaQuery();

        // 定义角色与对应匹配的 controlManId
        Map<String, String> roleControlManMap = new HashMap<>();
        roleControlManMap.put("1717361227428265985", "1717361227428265985"); // 日志-纪检岗
        roleControlManMap.put("1708113663597502466", "1708113663597502466"); // 检查-检查科科长岗位

        // 优先根据角色匹配，否则走用户id
        String controlManId = roleControlManMap.getOrDefault(currentRolesId, currentUserId);

        // 查询条件
        queryWrapper1.like(WorkriskControlEntity::getControlMan1, controlManId)
                .eq(WorkriskControlEntity::getTaxorgcode, currentDeptId);
        queryWrapper1.ne(WorkriskControlEntity::getStateCode, "3");
        int count1 = workriskControlService.count(queryWrapper1);
        // 提醒数量
        LambdaQueryWrapper<WorkriskRisk1Entity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.and((wrapper) -> wrapper.or().like(WorkriskRisk1Entity::getRiskManJcry, currentUserId)
                .or().like(WorkriskRisk1Entity::getRiskManSlry, currentUserId)
                .or().like(WorkriskRisk1Entity::getRiskManXary, currentUserId)
                .or().like(WorkriskRisk1Entity::getRiskManTzsry, currentUserId));
        queryWrapper.eq(WorkriskRisk1Entity::getRiskType, "6");
        queryWrapper.eq(WorkriskRisk1Entity::getTaxorgcode, currentDeptId);
        int count2 = workriskRisk1Service.count(queryWrapper);
        List<String> list = new ArrayList<>();
        list.add(String.valueOf(count1));
        list.add(String.valueOf(count2));
        return DataResult.success(list);
    }

    @PostMapping("/getYqsqSl")
    @ApiOperation(value = "获取首页获取延期申请数量")
    public DataResult getYqsqSl() {
        return null;
    }

    /**
     * 获取MP3提醒声音
     */
    @GetMapping("/getMp3Sy")
    @ApiOperation(value = "获取提醒声音")
    public void getMp3Sy(HttpServletResponse response, HttpServletRequest request) {

        String database = fileUploadProperties.getPath() + "/template/" + "reminderSound.mp3";

        // 文件目录（偷懒没有改变量，名称，此处和FTP没关系，就是文件的绝对路径）
        // 也就是 File music = new
        // File("C:\Users\Administrator\AppData\Local\Temp\a.mp3");
        File music = new File(database);
        String range = request.getHeader("Range");
        // 开始下载位置
        long startByte = 0;
        // 结束下载位置
        long endByte = music.length() - 1;
        // 有range的话
        if (range != null && range.contains("bytes=") && range.contains("-")) {
            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String[] ranges = range.split("-");
            try {
                // 判断range的类型
                if (ranges.length == 1) {
                    // 类型一：bytes=-2343
                    if (range.startsWith("-")) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                    // 类型二：bytes=2343-
                    else if (range.endsWith("-")) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                // 类型三：bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }
            } catch (NumberFormatException e) {
                startByte = 0;
                endByte = music.length() - 1;
            }
        }
        // 要下载的长度
        long contentLength = endByte - startByte + 1;
        // 文件名
        String fileName = music.getName();
        // 文件类型
        String contentType = request.getServletContext().getMimeType(fileName);
        // 各种响应头设置
        // 参考资料：https://www.ibm.com/developerworks/cn/java/joy-down/index.html
        // 坑爹地方一：看代码
        response.setHeader("Accept-Ranges", "bytes");
        // 坑爹地方二：http状态码要为206
        response.setStatus(206);
        response.setContentType(contentType);
        response.setHeader("Content-Type", contentType);
        /* 这里文件名换你想要的，inline表示浏览器直接实用（我方便测试用的）
         * 参考资料：http://hw1287789687.iteye.com/blog/2188500
         * response.setHeader("Content-Disposition", response.setHeader("Content-Disposition",
         */
        response.setHeader("Content-Length", String.valueOf(contentLength));
        // 坑爹地方三：Content-Range，格式为
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + music.length());
        BufferedOutputStream outputStream;
        // 已传送数据大小
        long transmitted = 0;
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(music, "r")) {
            try {
                outputStream = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[4096];
                int len = 0;
                randomAccessFile.seek(startByte);
                // 坑爹地方四：判断是否到了最后不足4096（buff的length）个byte这个逻辑（(transmitted + len) <=
                // contentLength）要放前面！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
                // 不然会会先读取randomAccessFile，造成后面读取位置出错，找了一天才发现问题所在
                while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                    transmitted += len;
                    // 停一下，方便测试，用的时候删了就行了
                    Thread.sleep(10);
                }
                // 处理不足buff.length部分
                if (transmitted < contentLength) {
                    len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
                    outputStream.write(buff, 0, len);
                }
                outputStream.flush();
                response.flushBuffer();
                randomAccessFile.close();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/getJinBaZhouQingkuangshuju")
    @ApiOperation(value = "获取首页数据接口")
    public DataResult getJinBaZhouQingkuangshuju() {
        return null;
    }

}
